package com.zxx.coolweather._wuguan;

import com.alibaba.fastjson.JSON;

import java.io.UnsupportedEncodingException;

/**
 * 代表请求任务的类HttpTask，让它实现Runnable接口，并且维护IHttpRequest和IHttpListener两个接口的引用.
 * 在将请求参数对象转换成字符串的过程中，我们使用了阿里的fastjson这个jar包。
 *
 * @author zxx on 2022/1/10
 */
public class HttpTask<T> implements Runnable {

    private IHttpRequest httpRequest;
    private IHttpListener httpListener;

    public <T> HttpTask(T requestInfo, String url, String method, IHttpRequest httpRequest, IHttpListener httpListener) {
        this.httpRequest = httpRequest;
        this.httpListener = httpListener;

        this.httpRequest.setUrl(url);

        if (method != null) {
            this.httpRequest.setMethod(method);
        } else {
            this.httpRequest.setMethod("GET");
        }

        //设置响应回调
        this.httpRequest.setHttpCallBack(httpListener);

        //设置请求参数
        if (requestInfo != null) {
            //将用户发送的请求参数对象转换成字符串
            String requestContent = JSON.toJSONString(requestInfo);

            //字符串转byte数组
            try {
                this.httpRequest.setRequestData(requestContent.getBytes("utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void run() {
        this.httpRequest.execute();
    }
}
